<template>
    <div class="specialty-management">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="请输入专业姓名" clearable @clear="handleSearch"
                @keyup.enter="handleSearch">
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>
            <el-button type="primary" :icon="Plus" @click="handleAddSpecialty">新增专业</el-button>
        </div>

        <!-- 专业列表 -->
        <el-table :data="filteredSpecialtys" stripe style="width: 100%" @row-click="handleRowClick">
            <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                :sortable="column.sortable" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="link" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="link" :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalSpecialtys"
                layout="total, sizes, prev, pager, next, jumper" @current-change="handlePageChange" />
        </div>

        <!-- 专业详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="专业详情" size="40%">
            <div v-if="selectedSpecialty">
                <h3>{{ selectedSpecialty.name }} 的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="名称">{{ selectedSpecialty.name }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>

        <!-- 新增/编辑专业对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑专业' : '新增专业'">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { GetSpecialty, PostSpecialty, PutSpecialty, DeleteSpecialty } from '@/api/SpecialtyService'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const columns = [
    { prop: 'name', label: '姓名', sortable: true }
]

// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: t('cannotBlank', { field: t('name') }), trigger: 'blur' },
        { min: 2, max: 5, message: '专业长度应为 2 到 20 个字符', trigger: 'blur' }
    ]
})

const specialtys = ref<any>([])
onMounted(async () => {
    specialtys.value = await GetSpecialty()
})

// 搜索功能
const searchQuery = ref('')
const filteredSpecialtys = computed(() => {
    return specialtys.value.filter(specialty =>
        specialty.name.includes(searchQuery.value))
})

// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalSpecialtys = computed(() => filteredSpecialtys.value.length)

// 专业详情
const drawerVisible = ref(false)
const selectedSpecialty = ref<any>(null)

// 新增/编辑专业
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref<any>({
    id: 0,
    name: "",
    idNumber: 0,
    gender: "",
    birthDate: new Date(),
    contactPhone: 0,
    address: "",
    departmentID: 2,
})

// 方法
const handleSearch = () => {
    currentPage.value = 1
}

const handleRowClick = (specialty) => {
    selectedSpecialty.value = specialty
    drawerVisible.value = true
}

const handleAddSpecialty = () => {
    form.value = {
        id: 0,
        name: "",
    }
    isEdit.value = false
    dialogVisible.value = true
}

const handleEdit = (specialty) => {
    // form.value = { ...specialty }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = {
        id: specialty.id,
        name: specialty.name,
    }
    isEdit.value = true
    dialogVisible.value = true
}

const handleDelete = (specialty) => {
    specialtys.value = specialtys.value.filter(p => p.id !== specialty.id)
    DeleteSpecialty(specialty.id)
}

const formRef = ref<any>(null)

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = specialtys.value.findIndex(p => p.id === form.value.id)
                specialtys.value[index] = { ...form.value }
                // PutSpecialtyApi(form.value.id, form.value)
                PutSpecialty(form.value.id, form.value)
                console.log('编辑专业:', form.value)
            } else {
                specialtys.value.push({ ...form.value, id: specialtys.value.length + 1 })
                PostSpecialty(form.value)
                console.log('新增专业:', form.value)
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })

}

const handlePageChange = (page) => {
    currentPage.value = page
}

</script>

<style scoped>
.specialty-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>